const { logInfo, logError } = require("../utils/logger");

const loggerMiddleware = (req, res, next) => {
  const start = Date.now();
  const requestId = req.headers["x-request-id"] || Date.now().toString(36);

  // 记录请求开始信息
  logInfo("请求开始", {
    requestId,
    method: req.method,
    url: req.url,
    query: req.query,
    body: req.body,
    ip: req.ip,
    userAgent: req.headers["user-agent"],
  });

  // 保存原始的 send 和 json 方法
  const originalSend = res.send;
  const originalJson = res.json;

  // 覆盖 res.send() 和 res.json() 方法以捕获响应体
  res.send = function (body) {
    res.locals.responseBody = body;
    return originalSend.apply(res, arguments);
  };

  res.json = function (body) {
    res.locals.responseBody = body;
    return originalJson.apply(res, arguments);
  };

  // 使用 res.on('finish') 来确保在响应发送后记录完成信息
  res.on("finish", () => {
    const ms = Date.now() - start;

    // 确保 responseBody 是一个字符串或 JSON 对象
    let formattedResponseBody;
    if (typeof res.locals.responseBody === "object") {
      formattedResponseBody = JSON.stringify(res.locals.responseBody); // 格式化输出
    } else if (typeof res.locals.responseBody === "string") {
      formattedResponseBody = res.locals.responseBody;
    } else {
      formattedResponseBody = "无响应体";
    }

    logInfo("请求完成", {
      requestId,
      method: req.method,
      url: req.url,
      status: res.statusCode,
      duration: `${ms}ms`,
      responseBody: formattedResponseBody,
      service: "user-service",
      timestamp: new Date().toISOString(),
    });
  });

  // 处理错误或连接关闭的情况
  res.on("close", () => {
    if (res.statusCode >= 400) {
      const ms = Date.now() - start;
      logError(
        "请求异常",
        new Error("Connection closed before response was completed"),
        {
          requestId,
          method: req.method,
          url: req.url,
          status: res.statusCode,
          duration: `${ms}ms`,
          body: req.body,
        }
      );
    }
  });

  next();
};

module.exports = loggerMiddleware;
